/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * UserProfile.java
 *
 * Created on Nov 7, 2010, 11:44:46 PM
 */

package lmclogistics;
import components.Image;
import components.Lightbox;
import components.NButton;
import components.Text;
import components.TextArea;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import sql.Sql;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Sonia Tan
 */
public class UserProfile extends javax.swing.JPanel {

    private Image bg;
    private static JTable userTable;
    private JScrollPane scroll;
    private DefaultTableModel model;
    private static TableColumn column;
    private NButton add;
    private NButton edit;
    private NButton delete;
    private TextArea filterField;
    private int selectedID;

    public UserProfile() {
        initComponents();
        setOpaque(false);
        setLocation(getCenterX(507), getCenterY(460));
        setSize(507, 460);
        setVisible(true);
        setBg();
        initTable();
        initButtons();
        initFilter();
        showTable();

    }

    public final void setBg(){
        bg = new Image("panel.png",507,460);

        add(bg,-1);

    }

    public int getCenterX(int x){

        int a = 919/2 - x/2;


        return a;
    }

    public int getCenterY(int x){

        int a = 577/2 - x/2;


        return a;
    }

    public void initTable(){
                userTable = new JTable(model);
		userTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		userTable.setFont(new Font("Lucida Grande", Font.PLAIN, 12));
		userTable.getTableHeader().setFont(new Font("Lucida Grande", Font.PLAIN, 12));
		scroll = new JScrollPane(userTable);
		scroll.setBounds(15,15,477,350);
		add(scroll,0);
    }

    public static void showTable(){
        try {
            String query = "SELECT * FROM User WHERE deleted=0";

            Connection connection = Sql.getSqlConnection();
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery(query);

            DefaultTableModel model = new DefaultTableModel(){
			    public boolean isCellEditable(int row, int column) {
			    	return false;
				}
			};
            model.addColumn("Code");
            model.addColumn("Username");
            model.addColumn("Access Level");

            while(rs.next()) {
               Vector rowData = new Vector () ;

               rowData.add(rs.getString("userCode"));
               rowData.add(rs.getString("userName"));
               if(rs.getString("userAccess").equals("0"))
                   rowData.add("Administrator");
               else if(rs.getString("userAccess").equals("1"))
                   rowData.add("Inventory");
               else if(rs.getString("userAccess").equals("2"))
                   rowData.add("Billing");
               model.addRow(rowData);
            }

            userTable.setModel(model);

            column = userTable.getColumnModel().getColumn(0);
            column.setPreferredWidth(159);
            column = userTable.getColumnModel().getColumn(1);
            column.setPreferredWidth(159);
            column = userTable.getColumnModel().getColumn(2);
            column.setPreferredWidth(159);

            Sql.closeSqlConnection(connection);

        } catch (Exception ex) {
            Logger.getLogger(Chassis.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public String getData(JTable table, int row_index, int col_index){
        return table.getModel().getValueAt(row_index, col_index).toString();
    }

    public void initButtons(){

        edit = new NButton("Edit",175 , 370);
        edit.setSize(157,25);
        add(edit,0);

        add = new NButton("Add", 15, 370);
        add.setSize(157,25);
        add(add,0);

        delete = new NButton("Delete", 335, 370);
        delete.setSize(157,25);
        add(delete,0);

        buttonlisteners();
    }

    public void buttonlisteners()
    {
        edit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
               EditUser et;
               if (userTable.getSelectedRow() != -1)
               {
                   selectedID = Integer.parseInt(getData(userTable,userTable.getSelectedRow(),0));
                   et = new EditUser(selectedID);
               }
               else
               {
                   SelectRow sr = new SelectRow("edit");
               }
            }
        });

        add.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                AddUser ac = new AddUser();
            }
        });

        delete.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                ConfirmDelete del;
                if (userTable.getSelectedRow() != -1)
                    del = new ConfirmDelete(6,getData(userTable,userTable.getSelectedRow(),0));
                else
                {
                    SelectRow sr = new SelectRow("delete");
                }
            }
        });
    }


    public void initFilter(){
        Text filter = new Text();

        filter.inText("Keywords:", 20, 400);
        add(filter,0);
        filterField = new TextArea();
        filterField.initText(200, 25, 95, 398);
        filterField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                filterTable();
            }
        });

        add(filterField,0);
    }

    public void filterTable(){

        String key = filterField.getText()+"%";

        if(key.contains("dele") || key.contains("delet") || key.contains("delet") || key.contains("delete") || key.equals("deleted"))
        {
            try {
                String query = "SELECT * FROM user WHERE deleted=1";

                Connection connection = Sql.getSqlConnection();
                Statement stmt = connection.createStatement();
                ResultSet rs = stmt.executeQuery(query);

                DefaultTableModel model = new DefaultTableModel(){
                                public boolean isCellEditable(int row, int column) {
                                    return false;
                                    }
                            };
                model.addColumn("Code");
                model.addColumn("Username");
                model.addColumn("Access Level");

                while(rs.next()) {
                   Vector rowData = new Vector () ;

                   rowData.add(rs.getString("userCode"));
                   rowData.add(rs.getString("userName"));
                   if(rs.getString("userAccess").equals("0"))
                       rowData.add("Administrator");
                   else if(rs.getString("userAccess").equals("1"))
                       rowData.add("Inventory");
                   else if(rs.getString("userAccess").equals("2"))
                       rowData.add("Billing");
                   model.addRow(rowData);
                }

                userTable.setModel(model);

                column = userTable.getColumnModel().getColumn(0);
                column.setPreferredWidth(159);
                column = userTable.getColumnModel().getColumn(1);
                column.setPreferredWidth(159);
                column = userTable.getColumnModel().getColumn(2);
                column.setPreferredWidth(159);

                Sql.closeSqlConnection(connection);

            } catch(Exception ex) {
                Logger.getLogger(Chassis.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        else if(key.equals("%"))
        {
            showTable();
        }

        else {
        try {
            String query = "SELECT * FROM user WHERE (userCode LIKE '"+key+"' or userName LIKE '"+key+"' or userAccess LIKE '"+key+"') AND deleted=0";

            Connection connection = Sql.getSqlConnection();
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery(query);

            DefaultTableModel model = new DefaultTableModel(){
			    public boolean isCellEditable(int row, int column) {
			    	return false;
				}
			};
            model.addColumn("Code");
            model.addColumn("Username");
            model.addColumn("Access Level");

            while(rs.next()) {
               Vector rowData = new Vector () ;

               rowData.add(rs.getString("userCode"));
               rowData.add(rs.getString("userName"));
               if(rs.getString("userAccess").equals("0"))
                   rowData.add("Administrator");
               else if(rs.getString("userAccess").equals("1"))
                   rowData.add("Inventory");
               else if(rs.getString("userAccess").equals("2"))
                   rowData.add("Billing");
               model.addRow(rowData);
            }

            userTable.setModel(model);

            column = userTable.getColumnModel().getColumn(0);
            column.setPreferredWidth(159);
            column = userTable.getColumnModel().getColumn(1);
            column.setPreferredWidth(159);
            column = userTable.getColumnModel().getColumn(2);
            column.setPreferredWidth(159);

            Sql.closeSqlConnection(connection);

        } catch (Exception ex) {
            Logger.getLogger(Chassis.class.getName()).log(Level.SEVERE, null, ex);
        }
        }
    }

    public static void delData(String code){
         try {
            String query = "UPDATE user SET deleted= 1 WHERE userCode="+code;

            Connection connection = Sql.getSqlConnection();
            Statement stmt = connection.createStatement();
            stmt.executeUpdate(query);

            Sql.closeSqlConnection(connection);
        }   catch (Exception ex) {
            Logger.getLogger(Chassis.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents


    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables

}
